package com.msh.frame.web.util;

import com.alibaba.fastjson.JSONObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class HttpServletResponseUtil {

  public static HttpServletResponse getCurrentResponse() {
    ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
        .getRequestAttributes();
    if (null != requestAttributes) {
      return requestAttributes.getResponse();
    }
    return null;
  }

  public static void outJson(Object o, HttpServletResponse response) throws IOException {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json; charset=utf-8");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Headers",
        "Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild");
    response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
    response.setHeader("Vary", "Origin");
    PrintWriter out = response.getWriter();
    out.append(JSONObject.toJSONString(o));
  }

}
